// 本地存储工具

// 设置存储
export const setStorage = (key, value) => {
  try {
    uni.setStorageSync(key, value)
    return true
  } catch (error) {
    console.error('设置存储失败:', error)
    return false
  }
}

// 获取存储
export const getStorage = (key, defaultValue = null) => {
  try {
    const value = uni.getStorageSync(key)
    return value !== '' ? value : defaultValue
  } catch (error) {
    console.error('获取存储失败:', error)
    return defaultValue
  }
}

// 移除存储
export const removeStorage = (key) => {
  try {
    uni.removeStorageSync(key)
    return true
  } catch (error) {
    console.error('移除存储失败:', error)
    return false
  }
}

// 清空所有存储
export const clearStorage = () => {
  try {
    uni.clearStorageSync()
    return true
  } catch (error) {
    console.error('清空存储失败:', error)
    return false
  }
}

// 获取存储信息
export const getStorageInfo = () => {
  try {
    return uni.getStorageInfoSync()
  } catch (error) {
    console.error('获取存储信息失败:', error)
    return null
  }
}

// 用户相关存储
export const setUserInfo = (userInfo) => {
  return setStorage('userInfo', userInfo)
}

export const getUserInfo = () => {
  return getStorage('userInfo', {})
}

export const setToken = (token) => {
  return setStorage('token', token)
}

export const getToken = () => {
  return getStorage('token', '')
}

export const removeToken = () => {
  return removeStorage('token')
}

// 购物车相关存储
export const setCartData = (cartData) => {
  return setStorage('cartData', cartData)
}

export const getCartData = () => {
  return getStorage('cartData', [])
}

// 地址相关存储
export const setAddressList = (addressList) => {
  return setStorage('addressList', addressList)
}

export const getAddressList = () => {
  return getStorage('addressList', [])
}

// 搜索历史
export const setSearchHistory = (history) => {
  return setStorage('searchHistory', history)
}

export const getSearchHistory = () => {
  return getStorage('searchHistory', [])
}

// 添加搜索历史
export const addSearchHistory = (keyword) => {
  const history = getSearchHistory()
  const index = history.indexOf(keyword)
  if (index > -1) {
    history.splice(index, 1)
  }
  history.unshift(keyword)
  // 只保留最近10条
  const newHistory = history.slice(0, 10)
  return setSearchHistory(newHistory)
}

// 清空搜索历史
export const clearSearchHistory = () => {
  return removeStorage('searchHistory')
} 